package org.iteam.bank.mina.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigLoader {
	public static Map<String, String> params = new HashMap<String, String>();
	private static final Logger LOGGER = LoggerFactory.getLogger(ConfigLoader.class);
	static {
		loadJobConfig("init.config");
	}

	public static boolean containsKey(Object key) {
		return params.containsKey(key);
	}

	public static String get(String key, String defaultValue) {
		if (!params.containsKey(key)) {
			return defaultValue;
		}
		return params.get(key);
	}

	public static String get(String key) {
		return get(key, "");
	}

	public static boolean getBoolean(String key, boolean defaultValue) {
		if (!params.containsKey(key)) {
			return defaultValue;
		}
		return Boolean.valueOf(params.get(key));
	}

	public static Integer getInteger(String key, Integer defaultValue) {
		if (!params.containsKey(key)) {
			return defaultValue;
		}
		return Integer.valueOf(params.get(key));
	}

	@SuppressWarnings("unused")
	private static void loadJobConfig(String name) {
		try {
			LOGGER.info("开始加载配置文件：{}", name);
			ClassLoader cl = ConfigLoader.class.getClassLoader();
			java.io.InputStream in = null;
			if (cl != null) {
				in = cl.getResourceAsStream(name);
			} else {
				in = ClassLoader.getSystemResourceAsStream(name);
			}
			if (in == null) {
				// 用文件读写
				in = new java.io.BufferedInputStream(new java.io.FileInputStream(name));
			}
			if (in != null) {
				try {
					Properties properties = new java.util.Properties();
					// 装载配置文件
					properties.load(in);
					// 得到配置内容

					for (Object key : properties.keySet()) {
						params.put(String.valueOf(key), consume(properties, String.valueOf(key)));
					}
					properties.clear();
					LOGGER.info("加载配置文件成功：{}", name);

				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (Exception e) {
							LOGGER.error(ExceptionUtils.getStackTrace(e));
						}
					}
				}
			} else {
				LOGGER.error("配置文件 {} 未被找到.", name);
			}
		} catch (Exception e) {
			LOGGER.error(ExceptionUtils.getStackTrace(e));
		}
	}

	private static String consume(java.util.Properties p, String key) {
		String s = null;
		if ((p != null) && (key != null)) {
			s = p.getProperty(key);
		}
		try {
			s = new String(s.getBytes("iso-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		LOGGER.info("key:" + key + ",value:" + s);
		return s;
	}
}
